<template>
    <div class="test-container page-container">
      <!-- 搜索选项 -->
      <el-row class="M-B-5" ref="searchRef">
        <el-form :inline="true" class="form" v-model="searchForm">
          <el-form-item class="Form-Item" label="">
            <el-select v-model="searchForm.creater" style="width:150px;" placeholder="请选择创建者" clearable>
                <el-option v-for="(item,index) in userList" :key="index" :value="item.id" :label="item.username"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="Form-Item" label="创建时间：">
              <el-date-picker v-model="searchForm.sumTime" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间" />
          </el-form-item>

          <el-form-item class="Form-Item" label="">
            <el-input class="W-Search" v-model="searchForm.searchWord"  placeholder="请输入关键词" clearable ></el-input>
          </el-form-item>
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button type="warning" @click="reset">重置</el-button>
        </el-form>
      </el-row>
      <!-- 按钮组 -->
      <el-row class="M-B-5" ref="btnsRef">
        <el-button type="primary" @click="add('ADD')">添加公告</el-button>
        <el-button type="danger" @click="batchDel" >批量删除</el-button>
      </el-row>
      <!-- 表格 -->
      <el-row class="M-B-5" >
        <el-table :data="tableData" stripe style="width: 100%" border highlight-current-row :height="tableHeight" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column v-for="(item,index) in tableCols" :key="index" :prop="item.prop" :label="item.label" :min-width="item.minWidth">
            <template  #default="scope">
              <div v-if="item.prop=='create_id'">
                {{userList.length && toUserName(scope.row.create_id) }}
              </div>
              <!-- 操作 -->
              <div v-if="item.prop=='handle'">
                <el-button size="small" type="primary" @click="handleEdit(scope)">编辑</el-button>
                <el-button size="small" type="danger" @click="batchDel(scope.$index, scope.row)" >删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!-- 分页 -->
      <el-row ref="pageRef">
        <el-pagination
        :total="pageTotal"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :background="pageBackground"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      </el-row>
      <addNotice ref="addRoleRef" @RefreshListEmit ="reset"/>
    </div>
  </template>
  
  <script lang="ts">
  import { defineComponent, ref,reactive ,toRefs ,onMounted,nextTick,defineAsyncComponent } from 'vue'
  import { rolelistApi,createRoleApi, updateRoleApi,deleteRoleApi,bindMenuApi,rolesMenusApi} from '@/request/role'
  import { menuListApi} from '@/request/menu'
  import { getNoticeMsgApi,createNoticeMsgApi,updateNoticeMsgApi,consoleDelMsgApi} from '@/request/notice'
  import { getUsersApi} from '@/request/user'
  import { getCurrentInstance} from 'vue'
  import {useStore} from '@/store'
  import Pinterface from '@/config/Interface/Public'
  import addNotice from '@/components/notice/addNotice.vue'
  
  
  import Interface from '@/config/Interface/User'
  export default defineComponent({
    name: 'Vuex',
    components:{addNotice},
    setup() {
      const context = getCurrentInstance()?.appContext.config.globalProperties; //获取this
      const store = useStore()
      const reactiveData = reactive({
        // 表单
        searchForm:{
          searchWord:'',
          creater:'',
          sumTime:['',''],
        },
        // 表头
        tableCols:[
          {prop:'content',label:'内容',minWidth:200},
          {prop:'create_id',label:'创建者',minWidth:80},
          {prop:'create_time',label:'创建时间',minWidth:100},
          {prop:'update_time',label:'更新时间',minWidth:100},
          {prop:'handle',label:'操作',minWidth:100},
        ],
        // 表格数据项
        tableData:[],

        // 用户下拉
        userList:[]
      })
      
      let menusList:any[] = []
      const getMenuList = async () =>{
        const {data} = await menuListApi()
        menusList = data.data
      }
      // 获取公告列表
      const getNoticeList = async () => {
        const searchForm = JSON.parse(JSON.stringify(reactiveData.searchForm))
        const postData = {
            isNotice:true,
            create_id : searchForm.creater,
            sumTime : searchForm.sumTime,
            searchWord : searchForm.searchWord,
            pageSize:pageSize.value,
            currentPage:currentPage.value
        }
        const res = await getNoticeMsgApi(postData)
        if(res.data.code === 1 ){
          reactiveData.tableData = res.data.data.data
          pageTotal.value = res.data.data.total
        }
      }
      const toUserName = (id:number) => {
        return (reactiveData.userList.find((item:any)=>{return item.id == id}) as any).username
      }

      // 获取用户列表
      const getUsersList = async () => {
        const {data} = await getUsersApi({all:true})
        if(data.code === 1){
           reactiveData.userList = data.data
        }
      } 
  
      // 搜索
      const search = ()=>{
        getNoticeList()
      }
      // 重置
      const reset = () =>{
        // reactiveData.searchForm = new Interface.searchForm()
        reactiveData.searchForm.searchWord = ''
        reactiveData.searchForm.creater = ''
        reactiveData.searchForm.sumTime = ['','']
        currentPage.value = 1;
        search()
      }
  
      // dom节点
      const searchRef = ref();
      const btnsRef = ref();
      const pageRef = ref();
  
      //表格高度
      const tableHeight = ref(0);
  
      // 分页
      const currentPage = ref(1)
      const pageSize = ref(10)
      const pageTotal = ref(0)
      const pageBackground = ref(false)
  
      // 切换表格显示条数
      const handleSizeChange = (val: number) => {
        pageSize.value= val;
        getNoticeList()
      }
  
      // 切换页码
      const handleCurrentChange = (val: number) => {
        currentPage.value = val
        getNoticeList()
      }
  
      // 获取表格高度
      const getTableHeight = ()=>{
        nextTick(()=>{
          if(store!==undefined){
            tableHeight.value = context?.$utils.getTableHeight(store.state.cardHeight,[searchRef.value.$el,btnsRef.value.$el,pageRef.value.$el])
          }else{
            tableHeight.value = 653;
          }
        })
      }
  
      //表格多选列表
      const selections = ref<any[]>([])
      const handleSelectionChange = (val: Interface.tableData[]) => {
        selections.value = val
      }
  
      const addRoleRef = ref()
      // 创建
      const add = (Type:string,scope?:any) => {
        addRoleRef.value.trigger(Type,scope)
      }
  
      // 编辑
      const handleEdit = (scope:any) =>{
        add('EDIT',scope)
      }
  
  
      // 删除 批量删除
      const batchDel = async (index?:any,row?:any) => {
        let ids:number[] = []
        if(row){
          ids = [row.id]
        }else{
          if(!selections.value.length){
            ElMessage({
              message:"请先选择数据",
              type:"warning"
            })
            return
          }
          ids = selections.value.map(item=>item.id)
        }
        ElMessageBox.confirm(
          '确定删除？','删除公告',
          {confirmButtonText: '确定',cancelButtonText: '取消',type: 'error',}
        ).then(async () => {
          const postData = {ids}
          const res = await consoleDelMsgApi(postData)
          if(res.data.code === 1){
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            setTimeout(()=>{
              reset()
            },300)
          }
        }).catch(() => {
  
        })
      }
  
      const setPowersRef = ref()
      // 设置权限
      const setPowers = async (scope:any)=>{
        setPowersRef.value.trigger(scope)
      }
  
      // 挂载
      onMounted(()=>{
        getMenuList()
        getTableHeight()
        getNoticeList()
        getUsersList()
      })
  
      return {
        ...toRefs(reactiveData),
        searchRef,btnsRef,pageRef,
        tableHeight,getTableHeight,
        currentPage,pageSize,pageTotal,pageBackground,handleSizeChange,handleCurrentChange,
        search,reset,handleEdit,add,batchDel,
        handleSelectionChange,
        addRoleRef,getMenuList,setPowers,setPowersRef,
        getUsersList,toUserName
      }
    }
  })
  </script>
  
  <style scoped lang="stylus">
  
  </style>
  